#coding=utf-8
import urllib
from lib import logs
from template import tplfilter
import time

def toGB2312(s):
	s = str(s)
	return s.decode('utf-8').encode('gb2312')


@tplfilter('seturl')
def seturl(url, params="", **ages):
	param=""
	if params is not "":
		for p in params.keys():
			if ages.get(p) is None:
				ages[p] = params[p]
	param = urllib.urlencode(params)
	# for p in ages.keys():
	# 	if params.get(p) != '' and params.get(p) is not None:
	# 		param += p + "=" +str(ages[p]) + "&"
	urls = url + "?" + param
	return urls


def get(url, params=""):
	times = float(time.time())
	urls = seturl(url , params)
	f=urllib.urlopen(urls)
	s=f.read()
	times = float(time.time()) - float(times)
	logs.setlog("lib:http:GET:%s  %.3f ms" % (urls, float(times*1000)))
	return s


def post(url, params):
	times = float(time.time())
	param = urllib.urlencode(params)
	f = urllib.urlopen(url,param)
	times = float(time.time()) - float(times)
	logs.setlog( "lib:http:POST:%s  %.3f ms" % (seturl(url , params), float(times*1000)))
	return f.read()